﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Admx_Generator
{
    public partial class FrmOptions : Form
    {
        private System.Resources.ResourceManager resMan = new System.Resources.ResourceManager("Admx_Generator.Localization.LocalizedStrings", typeof(FrmOptions).Assembly);
        private System.Globalization.CultureInfo _currentCulture = System.Threading.Thread.CurrentThread.CurrentCulture;

        public FrmOptions()
        {
            InitializeComponent();

            List<char> commonAllowedChars = Utilities.GetAllowedCharacters();

            this.fltTxtBxNamespace.FilterMethod = EasyCompany.Controls.FilteredTextbox.FilterMethods.AllowedCharacters;
            this.fltTxtBxNamespace.AllowedCharacters.AddRange(commonAllowedChars);
            this.fltTxtBxNamespace.AllowedCharacters.Add('.');

            this.SetUI();
        }

        #region (Private Methods)

        /// <summary>
        /// Set UI accordingly to the application settings
        /// </summary>
        private void SetUI()
        {
            // Namespace Tab
            try
            {
                this.fltTxtBxNamespace.Text = Properties.Settings.Default.DefaultTargetNamespace;
            }
            catch (Exception) { }

            // Revision Tab
            try
            {
                this.chkBxAlignMajorVersion.Checked = Properties.Settings.Default.AlignMajorVersion;
                this.chkBxAlignMinorVersion.Checked = Properties.Settings.Default.AlignMinorVersion;
                this.chkBxAutoIncrementADMLMinorVersion.Checked = Properties.Settings.Default.AutoIncrementADMLMinorVersion;
                this.chkBxAutoIncrementADMXMinorVersion.Checked = Properties.Settings.Default.AutoIncrementADMXMinorVersion;
            }
            catch (Exception) { }

            // Folder Tab
            string workingFolder;

            try
            {
                workingFolder = Utilities.GetExpandedPath(Properties.Settings.Default.WorkingFolder);
                if (!System.IO.Directory.Exists(workingFolder))
                {
                    System.IO.Directory.CreateDirectory(workingFolder);
                }
            }
            catch (Exception) { workingFolder = String.Empty; }
            try
            {
                this.txtBxWorkingFolder.Text = workingFolder;
            }
            catch (Exception) { }

            //Culture Tab

            string allLanguages = Properties.Resources.LanguageCodes;
            string[] codes = allLanguages.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

            foreach (string code in codes)
            {
                try
                {
                    culture newCulture = new culture(new System.Globalization.CultureInfo(code));
                    this.cmbBxCultureAddCulture.Items.Add(newCulture);
                    this.cmbBxCultureThisOne.Items.Add(newCulture);
                }
                catch (Exception) { }
            }
            this.cmbBxCultureAddCulture.SelectedIndex = 0;
            this.cmbBxCultureThisOne.SelectedIndex = 0;
            this.rdBtnCultureMy.Text += " : (" + _currentCulture.DisplayName + ")";

            this.chkBxCultureAddCulture.Checked = Properties.Settings.Default.AddCulture;
            if (Properties.Settings.Default.AddCulture)
            {
                this.cmbBxCultureAddCulture.SelectedItem = new culture(new System.Globalization.CultureInfo(Properties.Settings.Default.AddThisCulture));
            }

            try
            {
                switch (Properties.Settings.Default.FallbackCultureOption)
                {
                    case "MyCulture":
                        this.rdBtnCultureMy.Checked = true;
                        break;
                    case "en-US":
                        this.rdBtnCultureEnUs.Checked = true;
                        break;
                    case "ThisOne":
                        this.rdBtnCultureThisOne.Checked = true;
                        this.cmbBxCultureThisOne.SelectedItem = new culture(new System.Globalization.CultureInfo(Properties.Settings.Default.FallBackCultureThisOne));
                        break;
                }
            }
            catch (Exception) { }
        }

        /// <summary>
        /// Save settings to the properties file.
        /// </summary>
        private void SaveSettingsToProperties()
        {
            // Namespace Tab
            try
            {
                Properties.Settings.Default.DefaultTargetNamespace = this.fltTxtBxNamespace.Text;
            }
            catch (Exception ex) { this.DisplayErrorMessage(ex.Message); }

            // Revision Tab
            try
            {
                Properties.Settings.Default.AlignMajorVersion = this.chkBxAlignMajorVersion.Checked;
                Properties.Settings.Default.AlignMinorVersion = this.chkBxAlignMinorVersion.Checked;
                Properties.Settings.Default.AutoIncrementADMLMinorVersion = this.chkBxAutoIncrementADMLMinorVersion.Checked;
                Properties.Settings.Default.AutoIncrementADMXMinorVersion = this.chkBxAutoIncrementADMXMinorVersion.Checked;
            }
            catch (Exception ex) { this.DisplayErrorMessage(ex.Message); }

            // Folder Tab
            try
            {
                Properties.Settings.Default.WorkingFolder = this.txtBxWorkingFolder.Text;
            }
            catch (Exception ex) { this.DisplayErrorMessage(ex.Message); }

            // Culture Tab
            try
            {
                if (this.rdBtnCultureMy.Checked)
                    Properties.Settings.Default.FallbackCultureOption = "MyCulture";
                else if (this.rdBtnCultureEnUs.Checked)
                    Properties.Settings.Default.FallbackCultureOption = "en-US";
                else if (this.rdBtnCultureThisOne.Checked)
                {
                    Properties.Settings.Default.FallbackCultureOption = "ThisOne";
                    Properties.Settings.Default.FallBackCultureThisOne = ((culture)this.cmbBxCultureThisOne.SelectedItem).CultureInfo.Name;
                }
            }
            catch (Exception ex) { this.DisplayErrorMessage(ex.Message); }

            try
            {
                Properties.Settings.Default.AddCulture = this.chkBxCultureAddCulture.Checked;
                if (this.chkBxCultureAddCulture.Checked)
                {
                    Properties.Settings.Default.AddThisCulture = ((culture)this.cmbBxCultureAddCulture.SelectedItem).CultureInfo.Name;
                }
            }
            catch (Exception ex) { this.DisplayErrorMessage(ex.Message); }

            try
            {
                Properties.Settings.Default.Save();
            }
            catch (Exception ex) { this.DisplayErrorMessage(ex.Message); }

        }

        /// <summary>
        /// Check user entries and allow or disallow the 'Ok' button accordingly
        /// </summary>
        private void ValidateData()
        {
            bool namespaceTab = !String.IsNullOrEmpty(this.fltTxtBxNamespace.Text) && this.fltTxtBxNamespace.Text.EndsWith(".");
            bool folderTab = System.IO.Directory.Exists(Utilities.GetExpandedPath(this.txtBxWorkingFolder.Text));
            bool fallbackCulture = true;

            if (this.rdBtnCultureMy.Checked && this.chkBxCultureAddCulture.Checked && ((culture)this.cmbBxCultureAddCulture.SelectedItem).CultureInfo.Equals(this._currentCulture))
                fallbackCulture = false;
            if (this.rdBtnCultureEnUs.Checked && this.chkBxCultureAddCulture.Checked && ((culture)this.cmbBxCultureAddCulture.SelectedItem).CultureInfo.Name == "en-US")
                fallbackCulture = false;
            if (this.rdBtnCultureThisOne.Checked && this.chkBxCultureAddCulture.Checked && ((culture)this.cmbBxCultureAddCulture.SelectedItem).CultureInfo.Equals(((culture)this.cmbBxCultureThisOne.SelectedItem).CultureInfo))
                fallbackCulture = false;

            this.btnOk.Enabled = namespaceTab && folderTab && fallbackCulture;
            this.txtBxWorkingFolder.BackColor = folderTab ? SystemColors.Window : Color.DarkOrange;
            this.fltTxtBxNamespace.BackColor = namespaceTab ? SystemColors.Window : Color.DarkOrange;
            this.chkBxCultureAddCulture.ForeColor = fallbackCulture ? SystemColors.ControlText : Color.Red;
            this.lblAdditionalCultureError.ForeColor = fallbackCulture ? Color.Transparent : Color.Red;
        }

        /// <summary>
        /// Display an error message
        /// </summary>
        /// <param name="exceptionMessage">Message from the thrown exception that will display at the end of the message</param>
        private void DisplayErrorMessage(string exceptionMessage)
        {
            System.Windows.Forms.MessageBox.Show(this.GetLocalizedString("AnErrorOccurredWhileSavingSettings") + "\r\n[ " + exceptionMessage + " ]");
        }

        /// <summary>
        /// Returns a localized string depending of the current culture.
        /// </summary>
        /// <param name="unlocalizedString">string to localized.</param>
        /// <returns>the localized string.</returns>
        protected string GetLocalizedString(string unlocalizedString)
        {
            string result = string.Empty;

            try
            {
                result = resMan.GetString(unlocalizedString);
                if (!string.IsNullOrEmpty(result))
                    return result;
            }
            catch (Exception) { }

            return "Missing_Localized_String_For(" + ((unlocalizedString != null) ? unlocalizedString : "null") + ")";
        }

        #endregion (Private Methods)

        #region (UI Management)

        private void filteredTextbox_TextChanged(object sender, EventArgs e)
        {
            ValidateData();
        }

        private void chkBxRevision_CheckedChanged(object sender, EventArgs e)
        {
            this.ValidateData();
        }

        private void txtBxWorkingFolder_TextChanged(object sender, EventArgs e)
        {
            this.ValidateData();
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fldBrowserDlg = new FolderBrowserDialog();

            fldBrowserDlg.ShowNewFolderButton = true;
            fldBrowserDlg.SelectedPath = Utilities.GetExpandedPath(this.txtBxWorkingFolder.Text);
            if (fldBrowserDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                this.txtBxWorkingFolder.Text = fldBrowserDlg.SelectedPath;
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            this.SaveSettingsToProperties();
            this.Close();
        }

        private void rdBtnCulture_CheckedChanged(object sender, EventArgs e)
        {
            this.cmbBxCultureThisOne.Enabled = this.rdBtnCultureThisOne.Checked;
            this.ValidateData();
        }

        private void chkBxCultureAddCulture_CheckedChanged(object sender, EventArgs e)
        {
            this.cmbBxCultureAddCulture.Enabled = this.chkBxCultureAddCulture.Checked;
            this.ValidateData();
        }

        private void cmbBxCulture_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.ValidateData();
        }

        #endregion (UI Management)
    }
}
